﻿using System;
using Tiny.Imaging.Filter.ChannelBlendLibrary;
using Tiny.Imaging.Filter.PixelLibrary;

namespace Tiny.Imaging.Filter.PointFilter
{
    public class GrayscaleFilter : BaseFilter.BaseFilter
    {
        private readonly float _b;
        private readonly float _g;
        private readonly int _opacity;
        private readonly float _r;

        public GrayscaleFilter(int r = 30, int g = 59, int b = 11, Func<int, int, int> blend = null, int opacity = 100)
            : base(blend, opacity)
        {
            _r = r / 100.0f;
            _g = g / 100.0f;
            _b = b / 100.0f;
            _opacity = opacity;
        }

        public override int Process(Rgba rgba)
        {
            int lum = MathLibrary.MathLibrary.Clamp(rgba.R * _r + rgba.G * _g + rgba.B * _b);
            if (_opacity == 100)
            {
                rgba.R = rgba.G = rgba.B = lum;
            }
            else
            {
                rgba.R = ChannelBlend.Alpha(rgba.R, lum, _opacity / 100.0f);
                rgba.G = ChannelBlend.Alpha(rgba.G, lum, _opacity / 100.0f);
                rgba.B = ChannelBlend.Alpha(rgba.B, lum, _opacity / 100.0f);
            }

            return rgba.ToInteger();
        }
    }
}